package com.xoa.plugin.ct;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xoa.dao.work.WorkMapper;
import com.xoa.global.proxy.TriggerSubject;
import com.xoa.model.nccloud.NCCInterfaceLog;
import com.xoa.model.nccloud.NccPsninfo;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.TriggerPlugIn;
import com.xoa.service.nccloud.INCCInterFaceLogService;
import com.xoa.service.nccloud.INCCPsndocService;
import com.xoa.service.nccloud.INCCloudService;
import com.xoa.util.DateUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


/**
 * 城投---人事个人离职表单
 */
@Service
public class CTHRPsnLeavePushTrigger {

    /*
    接口工具
     */
    @Autowired
    private INCCloudService nccloudService;

    //表数据
    private TriggerPlugIn tri = null;
    @Autowired
    INCCInterFaceLogService logService;

    @Autowired
    INCCPsndocService psndocService;

    @Autowired
    private WorkMapper workMapper;
    //人员对象
    private  NccPsninfo nccPsninfo=null;


    public ToJson doRun( TriggerPlugIn tri)throws Exception {


        this.tri =tri;
        //当前表单id
        String run_id = tri.getRunId();
        //表id
        String tableName = tri.getFlowId();
        String reqeustBody=null;
        ToJson toJson=new ToJson();

        try {

            //====1、判断是否为新增人员离职办理表单
            if (StringUtils.isNotBlank(run_id) && tableName.equals("303")) {



                //=====2、请求nc接口保存获取主键
                // 封装NC接口表所需json数据
                reqeustBody = onversioncDto(tri.getModify(), run_id);

                // 请求发送保存
                String result = nccloudService.sendApi(nccloudService.psnLeaveUrl, reqeustBody);

                //转换json对象
                JSONObject rsjson = JSON.parseObject(result);
                //判断请求是否错误
                if (rsjson.getIntValue("code") == 1) {



                    //=====4、提交动作接口
                    // 接口调用成功 -- 取NC单据主键 pk_hi_stapply 存到记录行中
                    String pk = rsjson.getJSONObject("data").getString("pk_hi_stapply");
                    String billtype = rsjson.getJSONObject("data").getString("pk_billtype");

                    //保存单据主键和类型
                    this.saveBills(pk,billtype,run_id);

                    //请求发送保存json日志保存
                    this.saveLog(pk,reqeustBody,"城投人事个人离职303run_id:"+run_id+"人员保存true",result,"1");

                    // 提交NC单据动作
                    //{"pk":"1001ZZ100000002R2LFJ","billType":"6115","checkNote":"","approveResult":"Y","action":"APPROVE"}
                    JSONObject[] jsonObjectRs = this.billsAction(pk,billtype,"","","SAVE");
                    //单据保存动作是否错误
                    if (jsonObjectRs[1].getIntValue("code") == 1) {

                        //请求发送动作json日志保存
                        this.saveLog(pk,jsonObjectRs[0].toJSONString(),"城投人事个人离职303run_id:"+run_id+"人员保存动作true",jsonObjectRs[1].toJSONString(),"1");
                        toJson.setFlag(0);
                    } else {
                        //请求发送动作json日志保存
                        this.saveLog(pk,jsonObjectRs[0].toJSONString(),"城投人事个人离职303run_id:"+run_id+"人员保存动作false",jsonObjectRs[1].toJSONString(),"0");
                        toJson.setMsg(jsonObjectRs[1].getString("message"));
                        toJson.setFlag(1);
                    }
                } else {
                    //请求发送保存json日志保存
                    this.saveLog("",reqeustBody,"城投人事个人离职303run_id:"+run_id+"人员保存false",result,"0");
                    toJson.setFlag(1);
                    toJson.setMsg(rsjson.getString("message"));

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            //请求发送保存json日志保存
            this.saveLog("","","城投人事个人离职303run_id:"+run_id+"false",e.getMessage(),"0");
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());

        }
        return toJson;
    }

    /**
     * 表单数据拼接json
     *
     * @param formdata
     * @param runId
     * @return
     * @throws Exception
     */

    public String onversioncDto(String formdata, String runId) throws Exception {

        //将表单数据json数组解析List<Map<String, Object>>
        List<Map<String, Object>> data = JSONArray.parseObject(formdata, List.class);
        JSONObject jsonObject = new JSONObject();

        for (Map<String, Object> datum : data) {
            switch (datum.get("key").toString()) {

                case "DATA_6"://离职时间
                    jsonObject.put("effectdate",datum.get("value"));//生效日期
                    break;
                case "DATA_8"://审 批 流 程
                    break;
                case "DATA_14"://离职类型
                    jsonObject.put("pk_trnstype", "0302"); //调配类型
                    break;
                case "DATA_61"://部门

                    break;
                case "DATA_64"://职务
                    break;
                case "DATA_66"://入职时间
                    break;
                case "DATA_78"://人员编码

                    if(null!=datum.get("value")||datum.get("value")!=""){
                        //"10000004"根据人员编码获取人员信息datum.get("value").toString()
                        nccPsninfo = new NccPsninfo();
                        nccPsninfo.setCode(datum.get("value").toString().indexOf(",")>=0?datum.get("value").toString().substring(0,datum.get("value").toString().length()-1):datum.get("value").toString());
                        List<NccPsninfo> psninfoList = psndocService.selectPsn(nccPsninfo);
                        if (psninfoList.size() > 0&&null!=psninfoList){
                            nccPsninfo = psninfoList.get(0);
                        }else {
                            throw new RuntimeException("根据人员编号查询不到人员信息！");

                        }
                    }else {
                        throw new RuntimeException("人员编号为空！");
                    }
                    jsonObject.put("pk_psndoc",nccPsninfo.getCode()); //人员

                    if (jsonObject.getString("pk_psndoc").equals("")||null==jsonObject.getString("pk_psndoc")){
                        throw new RuntimeException("接口保存的pk_psndoc字段为空！");
                    }
                    break;

            }
        }




        jsonObject.put("sreason","01"); //异动原因

        jsonObject.put("isend", "Y"); //终止
        jsonObject.put("isrelease", "N"); //解除
        jsonObject.put("addreason", ""); //加入理由  f
        jsonObject.put("apply_date", DateUtil.format(tri.getSendTime(), "yyyy-MM-dd")); //申请日期
        String[] dateArry = jsonObject.getString("apply_date").split("-");
        jsonObject.put("bill_code", "CTRSLZ" + dateArry[0] + "" + dateArry[1] + "" + runId); //申请单编号
        jsonObject.put("ifaddblack", "N");//是否加入黑名单

        jsonObject.put("ifaddpsnchg", "N");//跨组织调配增加流动记录
        jsonObject.put("ifendpart", "N"); //结束兼职
        jsonObject.put("ifsynwork", "Y"); //同步工作履历
        jsonObject.put("isdisablepsn", "Y"); //停用离职人员

        jsonObject.put("ishrssbill", "N"); //是否自助
        jsonObject.put("isneedfile", "N"); //附件必传

        jsonObject.put("trial_flag", "N"); //试用
        jsonObject.put("newpk_dept",nccPsninfo.getPkDeptCode()); //新部门
        jsonObject.put("newpk_job", ""); //新职务  f
        jsonObject.put("newpk_job_type", ""); //新职务类型  f
        jsonObject.put("newpk_jobgrade", ""); //新职级  f
        jsonObject.put("newpk_jobrank", ""); //新职等  f
        jsonObject.put("newpk_org", nccPsninfo.getPkOrgCode()); //新组织108
        jsonObject.put("newpk_post", "");//新岗位  f
        jsonObject.put("newpk_postseries", "");//新岗位序列  f
        jsonObject.put("newpk_psncl","0202");//新人员类别0101
        jsonObject.put("newpoststat", ""); //新是否在岗  f
        jsonObject.put("newseries", ""); //新职务类别  f
        jsonObject.put("pk_billtype", "6115"); //单据类型    m
        jsonObject.put("pk_group","0001A210000000000GQS"); //集团    m
        jsonObject.put("pk_hi_org", nccPsninfo.getPkOrgCode()); //新人员信息组织
        jsonObject.put("pk_hi_stapply", ""); //调配申请单主键  f
        jsonObject.put("pk_hrcm_org", "108"); //新合同管理组织
        jsonObject.put("pk_old_hi_org", "108"); //原人员信息组织
        jsonObject.put("pk_old_hrcm_org", "10201"); //原合同管理组织
        jsonObject.put("pk_org",nccPsninfo.getPkOrgCode()); //人事组织 nccPsninfo.getPkOrgCode()

        jsonObject.put("stapply_mode", "1"); //调配方式
        jsonObject.put("assgid", "1"); //人员任职id   m
        jsonObject.put("workflow_state", "-1"); //workflow_state    m
        jsonObject.put("billmaker", tri.getUsers().getUserName()); //制单人tri.getUsers().getUserName()


        String danJuJson = "{\"billhead\":" + jsonObject.toJSONString() + "}";

        return danJuJson;
    }





    /**
     * 日志保存
     * @param pk
     * @param reqeustBody
     * @param name
     * @param result
     * @throws Exception
     */
    private void saveLog(String pk,String reqeustBody,String name,String result,String state)throws Exception{
        NCCInterfaceLog ncclog = new NCCInterfaceLog();
        ncclog.setBusinessNo(pk);
        ncclog.setContent(reqeustBody);
        ncclog.setName(name);
        ncclog.setResult(result);
        ncclog.setState(state);
        ncclog.setDisposeState("0");
        logService.save(ncclog);
    }


    /**
     * 单据动作
     * @param bills
     * @return
     * @throws Exception
     */
    public JSONObject[] billsAction(String... bills)throws Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pk",bills[0]);//单据主键
        jsonObject.put("billType",bills[1]);//单据类型编码
        jsonObject.put("checkNote",bills[2]);//批语
        jsonObject.put("approveResult",bills[3]);//审批结果
        jsonObject.put("action",bills[4]);//单据动作名称
        //请求发送动作
        String rs = nccloudService.sendApi(nccloudService.billactionUrl, jsonObject.toJSONString());

        return new JSONObject[]{jsonObject,JSON.parseObject(rs)};
    }

    /**
     * 保存单据信息
     * @param pk
     * @param billsType
     * @param run_id
     * @throws Exception
     */
    public void saveBills(String pk,String billsType,String run_id)throws Exception{
        // 保存主键的动作
        List<String> key = new ArrayList();
        key.add("pk_hi_stapply='"+pk+"'");
        key.add("billsType='"+billsType+"'");
        Map<String, Object> param = new HashMap();
        param.put("tableName", "flow_data_303");
        param.put("keys", key);
        param.put("runId", run_id);
        workMapper.update(param);
    }

}

